<?php

namespace App\Clients\YikaCar;

use App\Clients\BaseClient;
use App\Clients\JinShouFu\JinShouFuClient;
use App\Models\Account;
use App\Models\AccountSub;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Database\Eloquent\Model;
use Psr\Http\Message\ResponseInterface;

abstract class YikaCarClient extends JinShouFuClient
{
    protected $isJson = true;

    public function login(): void
    {
        $cookieJar = new CookieJar();
        $client = new Client([
            "verify"=>false,
            "http_errors"=>false,
            'cookies' => $cookieJar,
        ]);
        $url = "http://leader.szyika.com/Index/index.html";
        $client->get($url);
        $cookies = $cookieJar->toArray();
        $cookieStr = [];
        foreach ($cookies as $cookie){
            $cookieStr[] = $cookie["Name"]."=".$cookie["Value"];
        }
        $cookieStr = implode("; ",$cookieStr);
        $postData = [
            "account"=>$this->account->name,
            "pwd"=>$this->account->password,
        ];
        $url = "http://leader.szyika.com/Index/login";
        $response = $client->post($url,["form_params"=>$postData,"headers"=>[
            "Cookie"=>$cookieStr
        ]])->getBody()->getContents();
        $response = json_decode($response,true);
        $this->account->cookies = $cookieStr;
        $this->account->login_status = 1;
        $this->account->logout_at = date("Y-m-d H:i:s",time() + 86400 * 30);
        $this->account->save();

    }

    public function headers($other = []): array
    {
        $headers = [
            "User-Agent"=>'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.9 Safari/537.36',
            "Cookie"=>$this->account->cookies,
        ];
        return array_merge($headers,$other);
    }

    /**
     * @throws Exception
     */
    protected function isLogout(ResponseInterface $response){
        $content = $response->getBody()->getContents();
        if(str_contains($content,"艺卡智能代步车-登录")){
            $this->account->login_status = 0;
            $this->account->save();
            throw new Exception("掉线了");
        }
        return $this->isJson ? json_decode($content,true) : $content;
    }

}
